<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '文件预览',
    navigationStyle: 'custom',
  },
}
</route>
<template>
  <view style="background-color: #e3e3e3">
    <!-- <task-custom bgColor="bg-gradual-blue" :isBack="true">
      <block slot="backText">返回</block>
      <block slot="content">文件预览</block>
    </task-custom> -->
    <wd-navbar title="预览" :bordered="false" safeAreaInsetTop>
      <template #left>
        <wd-icon name="thin-arrow-left" size="22px" color="white" @click="goBack"></wd-icon>
      </template>
    </wd-navbar>
    <!-- #ifdef H5 -->
    <web-view
      :webview-styles="data.webviewStyles"
      :src="data.fileUrl"
      :fullscreen="false"
    ></web-view>
    <!-- #endif -->
    <!--<view :style="{ height: `calc(60px + ${StatusBar}px)` }"></view>
		 -->
  </view>
</template>

<script setup lang="ts">
import { reactive } from 'vue';

const data = reactive({
  webviewStyles: {
    progress: true,
  },
  fileUrl: '',
  isWeb: '0', // 是否预览网址 0文件 1网址
});

const goBack = () => {
  uni.navigateBack();
};

// 跳转链接
const lingWeb = (url) => {
  // 判断有没有http和https
  const reg = /^(https?:\/\/)/;
  if (!reg.test(url)) {
    url = 'http://' + url;
  }
  return url;
};

onLoad((options) => {
  let url = options.url;
  let isWeb = options.isWeb;
  if (isWeb == '1') {
    data.isWeb = '1';
  } else {
    data.isWeb = '0';
  }
  // let url = 'https://appthwater.thwater.com:30001/group1//M00/3A/61/wKgIA2P_UriAPmLQAAVC5YcWcQE096.pdf'
  if (!url) {
    uni.showToast({
      title: '文件读取失败，请重试',
      icon: 'none',
    });
    return false;
  }
  let baseURL = import.meta.env.VITE_PREVIEW_URL;
  // https://testappthwater.thwater.com:30080/preview/onlinePreview?url=
  const previewUrl = baseURL + '/preview/onlinePreview';

  //判断是不是ppt或者pptx 后面拼上&officePreviewType=pdf
  let shuxing = url.split('.')[url.split('.').length - 1];
  let pdfStr = '';
  if (shuxing == 'ppt' || shuxing == 'pptx') {
    pdfStr = '&officePreviewType=pdf';
  } else if (shuxing == 'xlsx') {
    pdfStr = '&officePreviewType=html';
  }
  if (data.isWeb == '0') {
    data.fileUrl = `${previewUrl}?url=${encodeURIComponent(
      uni.arrayBufferToBase64(str2ab(url)),
    )}${pdfStr}`;
  } else {
    data.fileUrl = `${lingWeb(url)}`;
  }

  console.log(data.fileUrl);
  init();
});

const init = () => {
  // #ifdef APP-PLUS
  let pages = getCurrentPages(); //getCurrentPages() 函数用于获取当前页面栈的实例
  let page = pages[pages.length - 1];
  plus.navigator.setFullscreen(false); //设置应用是否全屏显示
  let currentWebview = page.$getAppWebview(); //$getAppWebview() 可以得到当前webview的对象实例，从而实现对 webview 更强大的控制。
  createView(currentWebview); //创建界面
  // #endif
};

const createView = (currentWebview) => {
  let id = new Date().getTime();
  uni.getSystemInfo({
    success: (res) => {
      // 注意这里获得的高度宽度都是px，需要转换rpx
      // console.log(res.screenHeight); // 屏幕高度，包含导航栏
      // console.log(res.screenWidth); // 屏幕宽度
      // console.log(res.windowHeight); // 可使用窗口高度，不包含导航栏
      // console.log(res.windowWidth); // 可使用窗口宽度
      // console.log(this.phoneHeight)
      let top = 80;
      let height = res.screenHeight - top;
      let styles = {
        top: top + 'px',
        scalable: true,
        height: height + 'px',
        progress: {
          color: '#409eff',
        },
      };
      // console.log("fileUrl", this.fileUrl)
      var w = plus.webview.create(data.fileUrl, `i${id}`, styles);
      plus.webview.show(w); // 显示窗口
      currentWebview.append(w);
    },
  });
};

const str2ab = (str) => {
  let val = '';
  for (let i = 0; i < str.length; i++) {
    if (val === '') {
      val = str.charCodeAt(i).toString(16);
    } else {
      val += ',' + str.charCodeAt(i).toString(16);
    }
  }
  return new Uint8Array(
    val.match(/[\da-f]{2}/gi).map(function (h) {
      return parseInt(h, 16);
    }),
  ).buffer;
};
</script>
